package org.gdstash.ui.stash;

import org.gdstash.item.GDItem;
import org.gdstash.item.GDStash;
import org.gdstash.item.GDStashPage;
import org.gdstash.ui.GDLogoDialog;
import org.gdstash.ui.GDStashFrame;
import org.gdstash.ui.GDUITransfer;
import org.gdstash.ui.util.AdjustablePanel;
import org.gdstash.ui.util.GDStashInfoList;
import org.gdstash.util.GDConstants;
import org.gdstash.util.GDImagePool;
import org.gdstash.util.GDLog;
import org.gdstash.util.GDMsgFormatter;

import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.File;
import java.io.IOException;

public class GDSharedStashPane extends AdjustablePanel implements GDUIInventory {
    private GDStashFrame frame;
    private JTabbedPane tabPages;
    private int containerType;
    private GDContainerMapPane[] pnlPages;
    private JComboBox<String> cbSelStash;
    private JLabel lblSelMod;
    private JComboBox<String> cbSelMod;
    private GDStashInfoList.GDStashFileInfo info;
    private GDItem selItem;
    private GDContainerMapPane selPage;
    private JPanel pnlMain;
    private GDUITransfer uiTransfer;
    private boolean blockEvents;

    public GDSharedStashPane(final GDStashInfoList.GDStashFileInfo info, final int containerType, final GDStashFrame frame, final GDUITransfer uiTransfer) {
        this.info = info;
        this.containerType = containerType;
        this.frame = frame;
        this.uiTransfer = uiTransfer;
        this.pnlPages = new GDContainerMapPane[6];
        this.selItem = null;
        this.selPage = null;
        this.blockEvents = false;
        this.adjustUI();
        GroupLayout layout = null;
        GroupLayout.SequentialGroup hGroup = null;
        GroupLayout.SequentialGroup vGroup = null;
        this.pnlMain = this.buildMainPanel();
        layout = new GroupLayout(this);
        this.setLayout(layout);
        layout.setAutoCreateGaps(true);
        layout.setAutoCreateContainerGaps(true);
        hGroup = layout.createSequentialGroup();
        hGroup.addGroup(layout.createParallelGroup().addComponent(this.pnlMain));
        layout.setHorizontalGroup(hGroup);
        vGroup = layout.createSequentialGroup();
        vGroup.addGroup(layout.createParallelGroup().addComponent(this.pnlMain));
        layout.setVerticalGroup(vGroup);
    }

    @Override
    public void adjustUI() {
        final Font fntLabel = UIManager.getDefaults().getFont("Label.font");
        Font fntCombo = UIManager.getDefaults().getFont("ComboBox.font");
        if (fntCombo == null) {
            fntCombo = fntLabel;
        }
        Font fntTabbed = UIManager.getDefaults().getFont("TabbedPane.font");
        if (fntTabbed == null) {
            fntTabbed = fntLabel;
        }
        fntCombo = fntCombo.deriveFont((float) GDStashFrame.iniConfig.sectUI.fontSize);
        fntTabbed = fntTabbed.deriveFont((float) GDStashFrame.iniConfig.sectUI.fontSize);
        if (this.containerType == 1) {
            if (this.pnlPages[0] == null) {
                this.pnlPages[0] = new GDContainerMapPane(this, this.uiTransfer, GDImagePool.getSharedStashGrid());
            }
            if (this.pnlPages[1] == null) {
                this.pnlPages[1] = new GDContainerMapPane(this, this.uiTransfer, GDImagePool.getSharedStashGrid());
            }
            if (this.pnlPages[2] == null) {
                this.pnlPages[2] = new GDContainerMapPane(this, this.uiTransfer, GDImagePool.getSharedStashGrid());
            }
            if (this.pnlPages[3] == null) {
                this.pnlPages[3] = new GDContainerMapPane(this, this.uiTransfer, GDImagePool.getSharedStashGrid());
            }
            if (this.pnlPages[4] == null) {
                this.pnlPages[4] = new GDContainerMapPane(this, this.uiTransfer, GDImagePool.getSharedStashGrid());
            }
            if (this.pnlPages[5] == null) {
                this.pnlPages[5] = new GDContainerMapPane(this, this.uiTransfer, GDImagePool.getSharedStashGrid());
            }
        }
        if (this.containerType == 2) {
            if (this.pnlPages[0] == null) {
                this.pnlPages[0] = new GDContainerMapPane(this, this.uiTransfer, GDImagePool.getCraftingStashGrid());
            }
            if (this.pnlPages[1] == null) {
                this.pnlPages[1] = new GDContainerMapPane(this, this.uiTransfer, GDImagePool.getCraftingStashGrid());
            }
            if (this.pnlPages[2] == null) {
                this.pnlPages[2] = new GDContainerMapPane(this, this.uiTransfer, GDImagePool.getCraftingStashGrid());
            }
            if (this.pnlPages[3] == null) {
                this.pnlPages[3] = new GDContainerMapPane(this, this.uiTransfer, GDImagePool.getCraftingStashGrid());
            }
            if (this.pnlPages[4] == null) {
                this.pnlPages[4] = new GDContainerMapPane(this, this.uiTransfer, GDImagePool.getCraftingStashGrid());
            }
            if (this.pnlPages[5] == null) {
                this.pnlPages[5] = new GDContainerMapPane(this, this.uiTransfer, GDImagePool.getCraftingStashGrid());
            }
        }
        if (this.tabPages == null) {
            (this.tabPages = new JTabbedPane()).setTabPlacement(2);
            this.tabPages.add("I", this.pnlPages[0]);
            this.tabPages.add("II", this.pnlPages[1]);
            this.tabPages.add("III", this.pnlPages[2]);
            this.tabPages.add("IV", this.pnlPages[3]);
            this.tabPages.add("V", this.pnlPages[4]);
            this.tabPages.add("VI", this.pnlPages[5]);
        }
        this.tabPages.setFont(fntTabbed);
        this.tabPages.setMaximumSize(new Dimension(this.pnlPages[0].getPreferredWidth() + 80, this.pnlPages[0].getPreferredHeight()));
        if (this.cbSelStash == null) {
            (this.cbSelStash = new JComboBox<String>()).addActionListener(new StashSelectActionListener());
        }
        if (this.lblSelMod == null) {
            this.lblSelMod = new JLabel();
        }
        this.lblSelMod.setText(GDMsgFormatter.getString(GDMsgFormatter.rbUI, "TXT_MOD"));
        this.lblSelMod.setFont(fntLabel);
        if (this.cbSelMod == null) {
            (this.cbSelMod = new JComboBox<String>()).addActionListener(new ModSelectActionListener());
        }
        this.refreshStashSelection();
        this.cbSelStash.setFont(fntCombo);
        this.cbSelStash.setPreferredSize(new Dimension(270, fntCombo.getSize() + 8));
        this.cbSelStash.setMaximumSize(new Dimension(270, fntCombo.getSize() + 8));
    }

    private JPanel buildMainPanel() {
        GroupLayout layout = null;
        GroupLayout.SequentialGroup hGroup = null;
        GroupLayout.SequentialGroup vGroup = null;
        final JPanel panel = new JPanel();
        final JPanel pnlMod = this.buildModPanel();
        this.layoutStash();
        layout = new GroupLayout(panel);
        panel.setLayout(layout);
        layout.setAutoCreateGaps(true);
        layout.setAutoCreateContainerGaps(true);
        hGroup = layout.createSequentialGroup();
        hGroup.addGroup(layout.createParallelGroup().addComponent(this.cbSelStash).addComponent(pnlMod).addComponent(this.tabPages));
        layout.setHorizontalGroup(hGroup);
        vGroup = layout.createSequentialGroup();
        vGroup.addGroup(layout.createParallelGroup().addComponent(this.cbSelStash)).addGroup(layout.createParallelGroup().addComponent(pnlMod)).addGroup(layout.createParallelGroup().addComponent(this.tabPages));
        layout.setVerticalGroup(vGroup);
        layout.linkSize(1, this.cbSelStash, pnlMod);
        layout.linkSize(0, this.cbSelStash, pnlMod);
        layout.linkSize(0, this.cbSelStash, this.tabPages);
        return panel;
    }

    private JPanel buildModPanel() {
        GroupLayout layout = null;
        GroupLayout.SequentialGroup hGroup = null;
        GroupLayout.SequentialGroup vGroup = null;
        final JPanel panel = new JPanel();
        this.layoutStash();
        layout = new GroupLayout(panel);
        panel.setLayout(layout);
        layout.setAutoCreateGaps(true);
        layout.setAutoCreateContainerGaps(false);
        hGroup = layout.createSequentialGroup();
        hGroup.addGroup(layout.createParallelGroup().addComponent(this.lblSelMod)).addGroup(layout.createParallelGroup().addComponent(this.cbSelMod));
        layout.setHorizontalGroup(hGroup);
        vGroup = layout.createSequentialGroup();
        vGroup.addGroup(layout.createParallelGroup().addComponent(this.lblSelMod).addComponent(this.cbSelMod));
        layout.setVerticalGroup(vGroup);
        layout.linkSize(1, this.lblSelMod, this.cbSelMod);
        return panel;
    }

    public void refreshStashSelection() {
        this.blockEvents = true;
        int idx = -1;
        this.cbSelStash.removeAllItems();
        final String[] entries = GDStashInfoList.getStashInfos();
        for (int i = 0; i < entries.length; ++i) {
            this.cbSelStash.addItem(entries[i]);
            if (this.info != null && entries[i].equals(this.info.stashInfo)) {
                idx = i;
            }
        }
        this.cbSelMod.removeAllItems();
        if (GDStashInfoList.modDirs != null) {
            for (final String s : GDStashInfoList.modDirs) {
                this.cbSelMod.addItem(s);
            }
            if (GDStashInfoList.modDirs.isEmpty()) {
                this.cbSelMod.addItem("");
            }
        }
        this.blockEvents = false;
        if (idx == -1) {
            this.cbSelStash.setSelectedIndex(0);
        } else {
            this.cbSelStash.setSelectedIndex(idx);
        }
    }

    public void setStash(final GDStashInfoList.GDStashFileInfo info) {
        this.info = info;
        this.uiTransfer.setStash(info);
        GDStash stash = null;
        if (info != null) {
            stash = info.gdStash;
        }
        if (stash == null) {
            this.cbSelMod.setSelectedItem("");
            if (this.containerType == 1) {
                GDImagePool.buildSharedStash(8, 16);
            }
            if (this.containerType == 2) {
                GDImagePool.buildCraftingStash(8, 16);
            }
        } else {
            this.cbSelMod.setSelectedItem(stash.getModName());
            if (this.containerType == 1) {
                GDImagePool.buildSharedStash(stash.getWidth(), stash.getHeight());
            }
            if (this.containerType == 2) {
                GDImagePool.buildCraftingStash(stash.getWidth(), stash.getHeight());
            }
        }
        if (this.containerType == 1) {
            for (int i = 0; i < this.pnlPages.length; ++i) {
                this.pnlPages[i].setBGImage(GDImagePool.getSharedStashGrid());
            }
        }
        if (this.containerType == 2) {
            for (int i = 0; i < this.pnlPages.length; ++i) {
                this.pnlPages[i].setBGImage(GDImagePool.getCraftingStashGrid());
            }
        }
        this.setSelectedItem(null);
        this.layoutStash();
    }

    public GDContainerMapPane getCurrentPage() {
        final int index = this.tabPages.getSelectedIndex();
        return this.pnlPages[index];
    }

    public void layoutStash() {
        GDStash stash = null;
        if (this.info != null) {
            stash = this.info.gdStash;
        }
        int i = 0;
        if (stash != null) {
            for (final GDStashPage page : stash.getPages()) {
                if (i >= this.pnlPages.length) {
                    break;
                }
                page.setContainerType(this.containerType);
                final GDContainerPane container = new GDContainerPane(this.containerType, 0, 0, this.frame, this, this.uiTransfer);
                container.setContainer(page);
                this.pnlPages[i].clearContainers();
                this.pnlPages[i].addContainer(container);
                this.tabPages.setEnabledAt(i, true);
                ++i;
            }
        }
        while (i < this.pnlPages.length) {
            final GDContainerPane container2 = new GDContainerPane(this.containerType, 0, 0, this.frame, this, this.uiTransfer);
            this.pnlPages[i].clearContainers();
            this.pnlPages[i].addContainer(container2);
            this.tabPages.setEnabledAt(i, false);
            ++i;
        }
    }

    public void updateModSelection() {
        if (this.info == null) {
            return;
        }
        if (this.info.gdStash == null) {
            return;
        }
        String s = this.info.gdStash.getModName();
        if (s == null) {
            s = "";
        }
        this.cbSelMod.setSelectedItem(s);
    }

    public void deleteSelectedItem(final int action) {
        if (this.selItem == null) {
            return;
        }
        final boolean success = this.selPage.deleteItem(this.selItem, action, true);
        if (success) {
            this.setSelectedItem(null);
        }
    }

    public void moveSelectedItem(final int action, final int x, final int y) {
        if (this.selItem == null) {
            return;
        }
        final GDContainerMapPane page = this.getCurrentPage();
        final GDItem clone = this.selItem.clone();
        boolean success = page.addItem(clone, action, x, y);
        if (success) {
            success = this.selPage.deleteItem(this.selItem, action, true);
            if (success) {
                this.selItem = clone;
                this.selPage = page;
            }
        }
    }

    private boolean isModStashConflict(final String mod) {
        if (this.info == null) {
            return false;
        }
        if (this.info.gdStash == null) {
            return false;
        }
        if (GDStashFrame.iniConfig == null) {
            return false;
        }
        if (GDStashFrame.iniConfig.sectDir.savePath == null) {
            return false;
        }
        boolean conflict = false;
        try {
            String sMod = mod;
            if (sMod == null) {
                sMod = "";
            }
            String stashMod = this.info.gdStash.getModName();
            if (stashMod == null) {
                stashMod = "";
            }
            if (sMod.equals(stashMod)) {
                return false;
            }
            String dir = this.info.gdStash.getFile().getParentFile().getCanonicalPath();
            if (dir.length() > GDStashFrame.iniConfig.sectDir.savePath.length()) {
                dir = dir.substring(GDStashFrame.iniConfig.sectDir.savePath.length() + 1);
            } else {
                dir = "";
            }
            if (mod.equals(dir)) {
                return false;
            }
            dir = GDStashFrame.iniConfig.sectDir.savePath;
            if (!dir.endsWith(GDConstants.FILE_SEPARATOR)) {
                dir += GDConstants.FILE_SEPARATOR;
            }
            if (!sMod.equals("")) {
                dir = dir + sMod + GDConstants.FILE_SEPARATOR;
            }
            if (this.info.gdStash.isHardcore()) {
                dir += "transfer.gsh";
            } else {
                dir += "transfer.gst";
            }
            final File file = new File(dir);
            conflict = file.exists();
        } catch (IOException ex) {
        }
        return conflict;
    }

    @Override
    public GDItem getSelectedItem() {
        return this.selItem;
    }

    @Override
    public void setSelectedItem(final GDItem item) {
        this.selItem = item;
        if (item == null) {
            this.selPage = null;
        } else {
            (this.selPage = this.getCurrentPage()).layoutContainers();
        }
        this.uiTransfer.setSelectedItem(item, 1);
    }

    @Override
    public void refresh() {
        if (this.pnlPages != null) {
            for (int i = 0; i < this.pnlPages.length; ++i) {
                this.pnlPages[i].refresh();
            }
        }
    }

    public boolean addItem(final GDItem item, final int action, final int x, final int y) {
        if (item == null) {
            return false;
        }
        final GDContainerMapPane page = this.getCurrentPage();
        return page.addItem(item.clone(), action, x, y);
    }

    private class StashSelectActionListener implements ActionListener {
        @Override
        public void actionPerformed(final ActionEvent ev) {
            if (GDSharedStashPane.this.blockEvents) {
                return;
            }
            final GDLog log = new GDLog();
            final int idx = GDSharedStashPane.this.cbSelStash.getSelectedIndex();
            if (idx == -1) {
                return;
            }
            int i = 0;
            for (final GDStashInfoList.GDStashFileInfo info : GDStashInfoList.gdStashFileInfos) {
                if (i == idx) {
                    if (info.gdStash == null) {
                        info.gdStash = new GDStash(info.stashFile, log);
                    }
                    if (info.gdStash.hasStashErrors()) {
                        info.gdStash = null;
                        GDStashFrame.iniConfig.sectHistory.lastStash = "";
                    } else {
                        GDStashFrame.iniConfig.sectHistory.lastStash = info.fileName;
                    }
                    GDSharedStashPane.this.setStash(info);
                    break;
                }
                ++i;
            }
            log.showLog(GDSharedStashPane.this, GDMsgFormatter.getString(GDMsgFormatter.rbUI, "ERRORS"));
        }
    }

    private class ModSelectActionListener implements ActionListener {
        @Override
        public void actionPerformed(final ActionEvent ev) {
            if (GDSharedStashPane.this.blockEvents) {
                return;
            }
            final int idx = GDSharedStashPane.this.cbSelMod.getSelectedIndex();
            if (idx == -1) {
                return;
            }
            final String mod = (String) GDSharedStashPane.this.cbSelMod.getSelectedItem();
            if (GDSharedStashPane.this.info != null) {
                if (GDSharedStashPane.this.isModStashConflict(mod)) {
                    final GDLogoDialog dialog = new GDLogoDialog(GDMsgFormatter.getString(GDMsgFormatter.rbUI, "ERR_STASH_EXISTS"), 4, GDSharedStashPane.this.uiTransfer.getFrame());
                    dialog.setVisible(true);
                    String s = GDSharedStashPane.this.info.gdStash.getModName();
                    if (s == null) {
                        s = "";
                    }
                    GDSharedStashPane.this.cbSelMod.setSelectedItem(s);
                    return;
                }
                if (GDSharedStashPane.this.info.gdStash != null) {
                    GDSharedStashPane.this.info.gdStash.setModName(mod);
                }
                GDSharedStashPane.this.uiTransfer.checkSaveButton();
            }
        }
    }
}
